<template>
  <div class="AddOrUpdate_main add_container column_three">
    <div class="main_main">
      <el-form ref="form" :model="formData" :rules="rules" :inline="true">
        <el-form-item label="领料单号" prop="code">
          <CodeRuleInput
            :band-value.sync="formData.code"
            table-name="production_requisition"
            column-name="code"
            :is-edit="id"
          />
        </el-form-item>
        <el-form-item label="任务单号" class="clickChoose" prop="productTaskCode">
          <el-input v-model="formData.productTaskCode" placeholder="请选择" readonly />
          <a
            class="clickChoose_button"
            @click.prevent="chooseOrder"
          >
            <svg-icon icon-class="选择弹框" />
          </a>
        </el-form-item>
        <el-form-item label="领料人员">
          <el-input v-model="formData.requisitionName" placeholder="暂无" disabled />
        </el-form-item>
        <el-form-item label="领料日期">
          <el-date-picker
            v-model="formData.requisitionDate"
            type="date"
            placeholder="选择日期"
            :editable="false"
          />
        </el-form-item>
        <el-form-item label="备注" class="double">
          <el-input
            v-model="formData.remark"
            type="textarea"
            placeholder="请输入"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <div class="formItem_header">
        物料明细
        <div v-if="materialName.length > 0" class="MaterialName">
          <span class="MaterialNameIcon el-icon-warning" />
          <div v-for="item in materialName" :key="item" class="MaterialNameName">
            <span>{{ item }}</span>
          </div>
          <div class="MaterialNameText">物料暂无库存，无法领料！</div>
        </div>
        <!-- <div v-else-if="formData.hasRequire != '1'" class="MaterialName">
          <span class="MaterialNameIcon el-icon-warning" />
          <div class="MaterialNameName">
            {{ material }}
          </div>
          <div class="MaterialNameText">物料未维护生产输入，请前往工艺要求维护</div>
        </div> -->
        <div v-else />
        <div class="formItem_header_operate">
          <a class="formItem_header_operate_item" @click="addRow">
            <svg-icon icon-class="新增" />
            <div class="item_name">添加</div>
          </a>
          <a class="formItem_header_operate_item delete" @click="removeRow">
            <svg-icon icon-class="删除" />
            <div class="item_name">删除</div>
          </a>
        </div>
      </div>
      <div
        ref="table_container"
        class="table_container draggableTable"
      >
        <el-table
          ref="table"
          :data="tableData"
          :height="tableHeight"
          stripe
          border
          style="width: 99.9%;"
          :header-cell-class-name="headerCellClassName"
          @sort-change="(column)=>{sortChange(column, this)}"
          @selection-change="(val)=>{selectionChange(val, this)}"
        >
          <el-table-column type="selection" width="70" align="center" />
          <el-table-column label="领取数量" fixed="right" :min-width="SETTINGS.settings_decimalDigits_length" prop="requisitionNumber">
            <template slot-scope="scope">
              <el-input v-model="scope.row.requisitionNumber" placeholder="请输入" clearable />
            </template>
          </el-table-column>
          <el-table-column label="物料编码" min-width="120" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span>{{ scope.row.materialCode }}</span>
            </template>
          </el-table-column>
          <el-table-column label="物料名称" min-width="100" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span>{{ scope.row.materialName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="规格型号" min-width="100" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span>{{ scope.row.materialModel }}</span>
            </template>
          </el-table-column>
          <el-table-column label="物料分类" min-width="100">
            <template slot-scope="scope">
              <span>{{ scope.row.materialTypeName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="物料单位" min-width="100">
            <template slot-scope="scope">
              <span>{{ scope.row.materialUnitName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="库存数量" min-width="100">
            <template slot-scope="scope">
              <span>{{ scope.row.stockNum }}</span>
            </template>
          </el-table-column>
          <el-table-column label="需求数量" :min-width="SETTINGS.settings_decimalDigits_length">
            <template slot-scope="scope">
              <span>{{ scope.row.needNumber }}</span>
            </template>
          </el-table-column>
          <el-table-column label="已领数量" min-width="100">
            <template slot-scope="scope">
              <span>{{ scope.row.hasRequisitionNumber }}</span>
            </template>
          </el-table-column>
          <el-table-column label="可领数量" min-width="100">
            <template slot-scope="scope">
              <span>{{ scope.row.availableNumber }}</span>
            </template>
          </el-table-column>
          <el-table-column label="备注" min-width="200">
            <template slot-scope="scope">
              <el-input v-model="scope.row.remark" placeholder="请输入" clearable />
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <div class="main_bottom">
      <el-button type="cancel" @click.stop="cancel">取消</el-button>
      <el-button @click.stop="onSubmit('0')">保存</el-button>
      <el-button @click.stop="onSubmit('1')">提交</el-button>
    </div>
  </div>
</template>

<script>
import {
  addOrUpdate,
  getInfo,
  getInfoForRequisition
} from '@/api/ProductionManagement/pickingList'
// import { getInfo as getTaskInfo } from '@/api/ProductionManagement/taskSheet'
import chooseOrder from '../productionTaskSheet/chooseOrder.vue'
import addRow from './addRow.vue'
import moment from 'moment'
export default {
  name: 'AddOrUpdate',
  props: {
    layerid: {},
    id: {},
    defaultValue: {},
    isAdd: {}
  },
  data() {
    return {
      pageData: {
        pageNum: 1,
        pageSize: 9999,
        orderByColumn: 'updateTime',
        isAsc: 'desc'
      },
      material: '',
      formData: {
        id: '',
        code: '',
        productionTaskId: '',
        productTaskCode: '',
        requisitionName: '',
        requisitionBy: '',
        requisitionDate: '',
        remark: '',
        hasRequire: '1',
        data: []
      },
      tableData: [],
      tableHeight: '335',
      selections: [], // 表格当前页所选中的行
      selectionsAll: [], // 表格所有页选中的行
      materialName: [],
      mainId: 'id',
      peopleData: {},
      rules: {
        code: [
          { required: true, message: '领料单号不能为空', trigger: 'blur' }
        ],
        productTaskCode: [
          { required: true, message: '任务单号不能为空', trigger: 'change' }
        ]
      }
    }
  },
  created() {
    if (!this.id) {
      // 没有id就是新增
      Object.keys(this.defaultValue).forEach((key) => {
        // 给右边数据赋值
        this.formData[key] = this.defaultValue[key]
      })
    } else {
      // 有id就是编辑
      this.getInfo()
      this.formData.id = this.id
    }
  },
  mounted() {
    this.formData.requisitionName = this.$store.state.user.name
    this.formData.requisitionBy = this.$store.state.user.userId
    this.formData.requisitionDate = moment(new Date()).format('YYYY-MM-DD')
  },
  methods: {
    headerCellClassName(data) {
      if (['requisitionNumber'].indexOf(data.column.property) != -1) {
        return 'column_bt'
      }
    },
    handleSelectionChange() {

    },
    // 物料不足名称数组去重
    materialNameArr(arr) {
      var newArr = arr.filter(function(item, index) {
        return arr.indexOf(item) === index // 因为indexOf 只能查找到第一个
      })
      return newArr
    },
    // 去除物料名称不足最后一位逗号
    Removecommas(arr) {
      const arrTemp = arr
      if (arrTemp.length > 0) {
        if (arrTemp.indexOf('等') != -1) {
          arrTemp[arrTemp.length - 2] = arrTemp[arrTemp.length - 2].substr(0, arrTemp[arrTemp.length - 2].length - 1)
        } else {
          //
          arrTemp[arrTemp.length - 1] = arrTemp[arrTemp.length - 1].substr(0, arrTemp[arrTemp.length - 1].length - 1)
        }
        this.materialName = arrTemp
      }
    },
    chooseOrderCallBack(data) {
      this.formData.productionTaskId = data.id
      this.formData.productTaskCode = data.code
      // this.formData.hasRequire = data.hasRequire
      // this.material = data.materialName
      getInfoForRequisition(data.id).then(res => {
        this.tableData = []
        this.materialName = []
        const data3 = []
        if (res.data.engineeringRequirementMaterialData !== null) {
          const arr = this.$deepClone(res.data.engineeringRequirementMaterialData)
          arr.forEach(ele => {
            // ele['engineeringRequirementMaterialId'] = this.$deepClone(ele.id)
            ele.engineeringRequirementMaterialId = ele.id
            delete ele.id
            if (ele.stockNum && ele.stockNum == '0') {
              if (this.materialName.length < 5) {
                this.materialName.push(ele.materialName + ',')
                this.materialName = this.materialNameArr(this.materialName)
              } else {
                this.materialName.push('等')
              }
            } else {
              data3.push(ele)
            }
            if (ele.availableNumber != '/') {
              ele.requisitionNumber = Number(ele.availableNumber) > Number(ele.stockNum) ? ele.stockNum : ele.availableNumber
            }
            delete ele.remark
          })
          console.log(arr, 55555)
          this.materialName = this.materialNameArr(this.materialName)
          this.Removecommas(this.materialName)
          this.tableData = data3
        }
      })
    },
    chooseMaterialCallBack(data) {
      const data2 = this.$deepClone(data)
      data2.forEach(ele => {
        delete ele.remark
        if (!ele.requisitionNumber && ele.availableNumber != '/') {
          ele.requisitionNumber = Number(ele.availableNumber) > Number(ele.stockNum) ? ele.stockNum : ele.availableNumber
        }
      })
      this.tableData = data2
    },
    cellClassName(data) {
      if (data.column.property == 'operate') {
        if (data.rowIndex % 2 == 0) {
          // 单数行
          return 'fixed one'
        } else {
          // 双数行
          return 'fixed two'
        }
      }
    },
    rowClassName({ row, rowIndex }) {
      if (rowIndex == this.tableData.length - 1) {
        return 'addRow'
      }
    },
    addRow() {
      if (this.formData.productionTaskId) {
        this.$layer.iframe({
        // 弹框
          content: {
            content: addRow, // 传递的组件对象
            parent: this, // 当前的vue对象
            data: {
              selectedRow: this.tableData ? this.tableData : [],
              id: this.formData.productionTaskId ? this.formData.productionTaskId : ''
            } // props
          },
          area: ['880px', '700px'],
          title: '选择物料', // 标题
          shadeClose: false // 点击遮罩是否关闭
        })
      } else {
        this.$message.warning('请选择任务单号')
        return
      }
    },
    chooseOrder() {
      this.$layer.iframe({
        // 弹框
        content: {
          content: chooseOrder, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {
            id: this.formData.productionTaskId ? this.formData.productionTaskId : ''
          } // props
        },
        area: ['880px', '700px'],
        title: '选择任务单号', // 标题
        shadeClose: false // 点击遮罩是否关闭
      })
    },
    removeRow(row) {
      this.tableData = this.tableData.filter((ele) => this.selections.every((item) => ele.materialId != item.materialId))
    },
    getInfo() {
      getInfo(this.id).then((res) => {
        Object.keys(this.formData).forEach((key) => {
          // 给右边数据赋值
          this.formData[key] = res.data[key]
        })
        const arr = this.$deepClone(res.data.data)
        this.materialName = []
        arr.forEach(ele => {
          if (ele.stockNum == '0') {
            if (this.materialName.length < 5) {
              this.materialName.push(ele.materialName + ',')
              this.materialName = this.materialNameArr(this.materialName)
            } else {
              this.materialName.push('等')
            }
            ele.requisitionNumber = ele.needNumber
            delete ele.remark
          }
        })
        this.materialName = this.materialNameArr(this.materialName)
        this.Removecommas(this.materialName)
        console.log(this.materialName, 'this.materialName')
        this.tableData = this.formData.data
      })
    },
    // 提交
    onSubmit(num) {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.tableData.length > 0) {
            const data1 = this.tableData.filter(item => item.requisitionOrReturn == '1' && Number(item.availableNumber) < Number(item.requisitionNumber))// 筛选选是领退料限制的数据
            const data2 = this.tableData.filter(item => Number(item.stockNum) < Number(item.requisitionNumber))// 筛选选否领退料限制的数据
            if (data1.length > 0 && data1.length <= 3) {
              console.log(data1)
              const message = data1.map(item => item.materialName).toString()
              this.$message.warning(message + '物料的领取数量不得大于可领数量')
              return
            }
            if (data1.length > 0 && data1.length > 3) {
              const arr = data1.slice(0, 3)
              const message = arr.map(item => item.materialName).toString()
              this.$message.warning(message + '等物料的领取数量不得大于可领数量')
              return
            }
            if (data2.length > 0 && data2.length <= 3) {
              const message = data2.map(item => item.materialName).toString()
              this.$message.warning(message + '物料的领取数量不得大于库存数量')
              return
            }
            if (data2.length > 0 && data2.length > 3) {
              const arr2 = data2.slice(0, 3)
              const message = arr2.map(item => item.materialName).toString()
              this.$message.warning(message + '等物料的领取数量不得大于库存数量')
              return
            }
          }
          if (this.tableData.length == 0) {
            this.$message.warning('请添加物料明细')
            return
          }
          // console.log(this.tableData.filter(item => item.requisitionNumber > item.stockNum).length)
          // if (this.tableData && this.tableData.filter(item => Number(item.requisitionNumber) > Number(item.stockNum)).length > 0) {
          //   this.$message.warning('领取数量不能大于库存数量')
          //   return
          // }
          if (this.tableData && this.tableData.filter(item => !item.requisitionNumber).length > 0) {
            this.$message.warning('领取数量不能为空')
            return
          } else if (this.tableData && this.tableData.filter(item => item.requisitionNumber && !this.SETTINGS.reg_no_zero.test(item.requisitionNumber)).length) {
            this.$message.warning('领取数量未正确填写')
            return
          } else {
            this.formData.requisitionDate = this.formData.requisitionDate ? moment(this.formData.requisitionDate).format('YYYY-MM-DD') : ''
            this.formData.data = JSON.parse(JSON.stringify(this.tableData))
            this.formData.data.forEach(ele => {
              delete ele.id
            })
            addOrUpdate({ ...this.formData, status: num }).then((res) => {
              this.$message({
                message: res.msg,
                type: 'success'
              })
              this.$layer.close(this.layerid) // 关闭弹框
              this.$parent.getList() // 调用父组件的刷新方法
            })
          }
        }
      })
    },
    cancel() {
      this.$layer.close(this.layerid) // 关闭弹框
    }
    //
  }
}
</script>

<style lang="less" scoped>
.title {
  padding-left: 20px;
  padding-bottom: 20px;
  font-size: 24px;
  width: 100%;
}
.numberComponents {
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  align-items: center;
}
/deep/ .el-input-number.is-controls-right .el-input-number__increase {
  height: 15px;
}
.el-icon-remove {
  font-size: 25px;
  color: red;
  height: 100%;
  width: 100%;
  border: 0px;
  background-color: transparent;
}
/deep/ .el-form-item__content {
  margin-left: 0 !important;
}
/deep/ .el-form-item__label {
  text-align: right;
}
.expand_radio {
  /deep/ .el-form-item__content {
    text-align: left;
  }
}
.expand_container {
  .el-form-item {
    margin-bottom: 10px;
  }
  .expand_file {
    margin-bottom: 0px;
  }

  /deep/ .el-form-item__label {
    width: 130px !important;
  }
  /deep/ .el-form-item__content {
    width: 710px !important;
  }
}
.main_main {
  .form_padding {
    padding: 0 !important;
    /deep/ .el-form-item {
      margin-right: 0px;
    }
    /deep/ .el-form-item__label {
      width: 120px !important;
    }
    /deep/ .el-form-item__content {
      width: 270px;
    }
    .remark {
      /deep/ .el-form-item__content {
        width: 690px !important;
        height: 60px;
        overflow-y: auto;
      }
    }
  }
}
/deep/ .el-table th.el-table__cell > .cell {
  position: unset;
}
.order_header{
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  .info_button{
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: flex-end;
  }
}
.MaterialName {
  display: flex;
  padding: 15px;
  flex: 1;
  color:rgb(244,156,31);
  text-align: center;
  font-size: 16px;
  align-items: center;
  margin-bottom: 3px;

  .MaterialNameIcon {
    padding: 2px 5px 0 2px;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}
</style>
